﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace MessageSystem.Default.implement
{
    public class Selector
    {
        public void Poll(int millsecond)
        {
            if (allSockets.Count > 0)
            {
                readset_.Clear();
                writeset_.Clear();
                exceptionset_.Clear();

                readset_.AddRange(allSockets);
                writeset_.AddRange(allSockets);
                exceptionset_.AddRange(allSockets);

                Socket.Select(readset_, writeset_, exceptionset_, millsecond);
            }
        }

        public void Register(Socket socket)
        {
            allSockets.Add(socket);
        }

        public void UnRegister(Socket socket)
        {
            allSockets.Remove(socket);
        }

        public bool CanRead(Socket socket)
        {
            return readset_.Contains(socket);
        }

        public bool CanWrite(Socket socket)
        {
            return writeset_.Contains(socket);
        }

        public bool IsException(Socket socket)
        {
            return exceptionset_.Contains(socket);
        }

        private List<Socket> allSockets = new List<Socket>();
        private List<Socket> readset_ = new List<Socket>();
        private List<Socket> writeset_ = new List<Socket>();
        private List<Socket> exceptionset_ = new List<Socket>();
    }
}
